package org.duang.tags;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.DatagramSocket;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.duang.config.Config;
import org.duang.kit.ToolsKit;

@SuppressWarnings("serial")
public class MAC extends BodyTagSupport {

	private String name;
	private String sRemoteAddr;
	private int iRemotePort = 137;
	private byte[] buffer = new byte[1024];
	private DatagramSocket ds = null;

	/**
	 * 是否执行自定义标签的标签体,是否创建一个缓冲区对象捕获标签体的执行结果,从而让标签开发者在标签处理种对标签体的执行结果进行修改,
	 * 其返回值可以是一下三个: EVAL_BODY_INCLUDE(执行标签体), SKIP_BODY(跳过标签体),
	 * EVAL_BODY_BUFFERED(把标签体放到缓冲区中,以便进一步处理)
	 */
	@Override
	public int doStartTag() throws JspException {
		try {
			name = (ToolsKit.isEmpty(name)) ? Config.getProductCode() + "_MAC" : name;
			pageContext.getOut().write(buildGetMACHtml());
			// pageContext.getOut().write(url);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// return EVAL_BODY_INCLUDE; //执行doAfterBody()方法
		// return EVAL_BODY_BUFFERED;
		return SKIP_BODY;
	}

	/**
	 * EVAL_BODY_AGAIN(表示再执行标签体一次), SKIP_BODY(表示结束标签体执行继续执行doEndTag)
	 */
	@Override
	public int doAfterBody() throws JspException {
		return SKIP_BODY; // 表示结束标签体执行继续执行doEndTag
	}

	/**
	 * 控制是否执行结束标签后面的内容, 其返回值可以为: EVAL_PAGE(表示继续执行结束标签后面的jsp代码);
	 * SKIP_PAGE(表示忽略结束标签后面的jsp代码).
	 */
	@SuppressWarnings("static-access")
	@Override
	public int doEndTag() throws JspException {
		return this.EVAL_PAGE;
	}

	// 构建HTML
	public String buildGetMACHtml() {
		StringBuilder macStr = new StringBuilder();
		String osName = System.getProperty("os.name");
		String smac = "";
		try {
			if (osName.equalsIgnoreCase("linux")) {
				smac = getLinuxMac();
			} else {
				smac = getWinMac();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		macStr.append("<input type='hidden' id='_duangMac").append(name).append("_").append("' name='").append(name)
				.append("' value='").append(smac).append("'/>");

		return macStr.toString();
	}

	private String getWinMac() throws IOException {
		HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
		String sip = request.getHeader("x-forwarded-for");   
		if(sip == null || sip.length() == 0 || "unknown".equalsIgnoreCase(sip)) {   
		    sip = request.getHeader("Proxy-Client-IP");   
		}   
		if(sip == null || sip.length() == 0 || "unknown".equalsIgnoreCase(sip)) {   
		    sip = request.getHeader("WL-Proxy-Client-IP");   
		}   
		if(sip == null || sip.length() == 0 || "unknown".equalsIgnoreCase(sip)) {   
		    sip = request.getRemoteAddr();   
		}   
//		Process process = Runtime.getRuntime().exec("ipconfig -all" );		
		Process process = Runtime.getRuntime().exec("nbtstat -a " + sip); 
		InputStreamReader ir = new InputStreamReader(process.getInputStream(), "GBK");
		LineNumberReader input = new LineNumberReader(ir);
		String line=""; 
		String smac="";
		while ((line = input.readLine()) != null) {
			if (line.toLowerCase().indexOf("physical") > 0 || line.indexOf("物理地址") > 0) {
				smac = line.substring(line.indexOf("-") - 2);
				break;
			}
		}
		return smac;
	}

	private String getLinuxMac() throws IOException {
		Process process = Runtime.getRuntime().exec("cat /sys/class/net/eth0/address");
		InputStreamReader ir = new InputStreamReader(process.getInputStream());
		LineNumberReader input = new LineNumberReader(ir);
		String line = "";
		String smac = "";
		while ((line = input.readLine()) != null) {
			smac = line;
		}
		return smac;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}
